/**
 * 
 */
package neptune.web.client.controller;

import neptune.web.client.model.SerializableUser;
import neptune.web.client.services.user.UserService;
import neptune.web.client.view.ConsoleManager;
import neptune.web.client.view.OperativeView;
import neptune.web.client.view.SuperView;
import neptune.web.client.view.UserView;
import neptune.web.client.view.ViewManager;
import neptune.web.client.view.components.dialogs.AddUserDialog;
import neptune.web.client.view.components.dialogs.AddUserDialogListener;

import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 * 
 */
public class AddUserController implements AddUserDialogListener {

	/*
	 * (non-Javadoc)
	 * 
	 * @see neptune.web.client.view.components.AddUserDialogListener#addUserCommandGiven(java.lang.String,
	 *      java.lang.String, java.lang.String, java.lang.String,
	 *      neptune.web.client.view.components.AddUserDialog)
	 */
	public void addUserCommandGiven(final String username, String password,
			String email, final String role, final AddUserDialog sender) {

		SerializableUser user = new SerializableUser(username, role, password);
		user.setEmail(email);

		UserService.Util.getInstance().addUser(user, new AsyncCallback<Boolean>() {

			public void onSuccess(Boolean arg0) {
				String message = "User Added: " + username + " with role "
						+ role;
				sender.showMessage(message);
				ConsoleManager.addConsoleMessage(message, false);

				SuperView operative = (SuperView) ViewManager.getViewManager()
						.getViewByName(OperativeView.DEFAULT_TOKEN);
				UserView user = (UserView) operative
						.getViewByName(UserView.DEFAULT_TOKEN);
				user.reset();
				user.update();
			}

			public void onFailure(Throwable arg0) {
				String message = "User Adding failed: " + username + " Cause: "
						+ arg0.getMessage();
				sender.showMessage(message);
				ConsoleManager.addConsoleMessage(message, true);
			}

		});

	}

}
